package com.cskaoyan.order.biz.handler;

import com.cskaoyan.order.biz.context.CancelOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhuqiushi
 * @since 2022/09/21 16:38
 */
@Component
@Slf4j
public class CancelUpdateStockHandler extends AbstractTransHandler{
    @Autowired
    StockMapper stockMapper;
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CancelOrderContext cancelOrderContext = (CancelOrderContext) context;
        //对每个商品的库存做更改
        Stock stock = new Stock();
        List<OrderItem> orderItems = cancelOrderContext.getOrderItems();
        for (OrderItem orderItem : orderItems) {
            //这是要加上的库存数量
            Long buyNum = Long.valueOf(orderItem.getNum());
            stock.setItemId(orderItem.getItemId());
            stock.setStockCount(buyNum);
            //这是要减去的锁库存数量
            stock.setLockCount(-orderItem.getNum());
            stockMapper.updateStock(stock);
        }
        return true;
    }
}
